import csv
import json
from backend.eform.models import Eform, EformPairing
from logger.createlogger import create_logger
logger = create_logger(__name__)

class HierarchyChecksheet():
    _JSON_FILE_NAME = 'hierarchy_checksheet.json'
    _CSV_FILE_NAME = 'hierarchy_checksheet.csv'
    hc_dict = {}
    use_db= False
    def __init__(self,alt=False):

        # try:
        paris = EformPairing.objects.all()
        if paris.count()==0:
            self.hc_dict = self.loadFromJson(alt)
            if not self.hc_dict or self.hc_dict =={}:
                self.hc_dict = self.loadFromCsv(alt)
                self.saveAsJson()
            if not self.hc_dict or self.hc_dict == {}:
                logger.debug("CSV OR JSON NOT FOUND")
            # use_db = self.importToDatabase().count() > 0
            use_db = len(self.importToDatabase()) > 0
        # except Exception as ex:
        #     print(ex)
        #     logger.warn(ex)
        #     logger.warn("Exception of HierarchyChecksheet")

    def getJsonFilename(self,alt_fname=False):
        fname = "eform/"
        if alt_fname:
            fname = fname + alt_fname
            return fname
        return f"{fname}{self._JSON_FILE_NAME}"

    def getCSVFilename(self,alt_fname=False):
        fname = "eform/"
        if alt_fname:
            fname = fname + alt_fname
            return fname
        return f"{fname}{self._CSV_FILE_NAME}"

    def loadFromCsv(self,alt_fname=False):
        ret = {}
        fname = self.getCSVFilename(alt_fname)
        try:
            with open(fname,newline='') as csvFile:
                reader = csv.reader(csvFile,delimiter=',')
                for row in reader:
                    lv6, cs = row
                    lv6 = lv6.strip()
                    if lv6 not in ret:
                        ret[lv6] = []
                    if cs not in ret[lv6]:
                        ret[lv6].append(cs)
                    
        except Exception as ex :
            logger.debug(ex)
            return False
        return ret

    def loadFromJson(self,alt_fname=False):
        fname = self.getJsonFilename(alt_fname)
        jsonObject = False
        try:
            with open(fname) as jsonFile:
                jsonObject = json.load(jsonFile)
                jsonFile.close()
            return jsonObject
        except Exception as ex:
            logger.debug(ex)
            return {}

    def saveAsJson(self):
        try:
            j_str = json.dumps(self.hc_dict)
            fname = self.getJsonFilename()
            jsonFile = open(fname,"w")
            jsonFile.write(j_str)
            jsonFile.close()
        except Exception as ex:
            logger.debug(ex)

    def findChecksheets(self,key):
        logger.debug(f"{key=}")
     
        try:
            datas = EformPairing.objects.filter(level6=key)
            if datas.count() > 0:
                return [
                    d.formNo for d in datas
                ]
            return self.hc_dict[key]
        except Exception as ex:
            logger.debug(ex)
            return False


    def importToDatabase(self):
        logger.info("No Eform Parining record, importing...")
        create = []
        for eq,val in self.hc_dict.items():
            for fn in val:
                create.append(EformPairing(level6=eq,formNo=fn))
        created = EformPairing.objects.bulk_create(create)
        # logger.info(f"{created.count()} records imported.")
        logger.info(f"{len(created)} records imported.")
        return created